package com.zhongshengnetwork.rightbe.common.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
//import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.fastjson.JSONObject;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.Des;
import com.zhongshengnetwork.rightbe.common.QRCodeUtil;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.PublishSelectPicPopupWindow;
import com.zhongshengnetwork.rightbe.lang.activity.LangCommentActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.qrcode.QRCodeActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class AppQRCodeActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener{
    private final static String url = "http://a.app.qq.com/o/simple.jsp?pkgname=com.zhongshengnetwork.rightbe";//Constant.HOST+"downapp.do?";
    private final static String content = "言微句美，发现共鸣";
    private TopBarView topbar;
    private ImageView qrcodeImageView;
    private List<String> nameList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_qrcode);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        if (nameList == null){
            nameList = new ArrayList<String>();
            nameList.add("分享给微信好友");
            nameList.add("分享到微信朋友圈");
            nameList.add("分享给QQ好友");
            nameList.add("分享到QQ空间");
            nameList.add("分享到微博");
        }
        topbar.getRightTextView().setVisibility(View.VISIBLE);
        topbar.getRightTextView().setText("分享");
        topbar.getRightTextView().setTextSize(14);
        topbar.getRightTextView().setClickable(true);
        topbar.getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonUtils.isLogin() == false){
                    Intent intent = new Intent(AppQRCodeActivity.this, LoginActivity.class);
                    startActivity(intent);
                    return;
                }
                shareDownload();
            }
        });
        qrcodeImageView = (ImageView) findViewById(R.id.appqrcode_qrimg);
        final String filePath = getFileRoot(AppQRCodeActivity.this) + File.separator
                + "qr_" + System.currentTimeMillis() + ".jpg";

        //二维码图片较大时，生成图片、保存文件的时间可能较长，因此放在新线程中
        new Thread(new Runnable() {
            @Override
            public void run() {
                String content = Constant.HOST+"downapp.do?";
                int W = dip2px(AppQRCodeActivity.this,250.0f);
                boolean success = QRCodeUtil.createQRImage(content, W, W,
                        null,
                        filePath);

                if (success) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            qrcodeImageView.setImageBitmap(BitmapFactory.decodeFile(filePath));
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    //文件存储根目录
    private String getFileRoot(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File external = context.getExternalFilesDir(null);
            if (external != null) {
                return external.getAbsolutePath();
            }
        }

        return context.getFilesDir().getAbsolutePath();
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    private void shareDownload(){
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(AppQRCodeActivity.this)
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : nameList){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which == 1){
                        //分享给微信好友
                        shareToWX(1,url,content,"或源于你看了一部电影、看了一本书、看到了一句话、想到了一个点子、领悟到了一个道理，或展现你的独特见解，或表达你的人生感悟，或书写你的喜闻乐见。");
                    }else if (which == 2){
                        //分享到朋友圈
                        shareToWX(0,url,content,"或源于你看了一部电影、看了一本书、看到了一句话、想到了一个点子、领悟到了一个道理，或展现你的独特见解，或表达你的人生感悟，或书写你的喜闻乐见。");
                    }else if (which == 3){
                        //分享到qq
                        shareToQQ(0,content,"或源于你看了一部电影、看了一本书、看到了一句话、想到了一个点子、领悟到了一个道理，或展现你的独特见解，或表达你的人生感悟，或书写你的喜闻乐见。");
                    }else if (which == 4){
                        //qq空间
                        shareToQQ(1,content,"或源于你看了一部电影、看了一本书、看到了一句话、想到了一个点子、领悟到了一个道理，或展现你的独特见解，或表达你的人生感悟，或书写你的喜闻乐见。");
                    }else if (which == 5){
                        //微博
                        CustomApplication.WbShareType = 0;
                        CustomApplication.WbShareSourceId = "0";
                        CustomApplication.WbShareTitle = content;
                        CustomApplication.WbShareText = "一句不简单的话，或源于你看了一部电影、看了一本书、看到了一句话、想到了一个点子、领悟到了一个道理，或展现你的独特见解，或表达你的人生感悟，或书写你的喜闻乐见。";
                        CustomApplication.WbShareActionUrl = url;
                        Intent mIntent = new Intent(BroadcastDefine.WeiBo_Share_Action);
                        //发送广播
                        sendBroadcast(mIntent);
                    }
                }
            });
        }
        actionSheetDialog.show();
    }

    //分享到微信
    private void shareToWX(int type,String url,String title,String content){
        //初始化一个WXWebpageObject对象，填写url
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        //用WXWebpageObject对象初始化一个WXMediaMessage对象，填写标题、描述
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = content;
        Bitmap thumb = BitmapFactory.decodeResource(getResources(),R.mipmap.icon);
        msg.thumbData = CommonUtils.bitmapToByteArray(thumb,true);
        //构成一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.message = msg;
        req.scene = type==0 ? SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
        CustomApplication.mWxApi.sendReq(req);

    }

    //分享到qq
    private MyIUiListener mIUiListener = new MyIUiListener();
    class MyIUiListener implements IUiListener {
        @Override
        public void onComplete(Object o) {
            Log.e("TAG","分享成功");
        }

        @Override
        public void onError(UiError uiError) {
            Log.e("TAG","分享出错");
        }

        @Override
        public void onCancel() {
            Log.e("TAG","分享取消");
        }

        @Override
        public void onWarning(int i) {

        }
    }
    private Bundle params;
    private void shareToQQ(int type,String title,String content){
        params = new Bundle();
        if (type == 0){//分享给QQ好友
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 标题
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, content);// 摘要
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,"http://a.app.qq.com/o/simple.jsp?pkgname=com.zhongshengnetwork.rightbe");// 内容地址
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,"http://image.daydayrise.net/360@2x.png");// 网络图片地址
            params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "");//其它附加功能
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CustomApplication.mTencent.shareToQQ(AppQRCodeActivity.this, params, mIUiListener);
                }
            });
        }else {
            //分享到QQ空间
            params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE,QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
            params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);// 标题
            params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, content);// 摘要
            params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,"http://a.app.qq.com/o/simple.jsp?pkgname=com.zhongshengnetwork.rightbe");// 内容地址
            ArrayList<String> imgUrlList = new ArrayList<>();
            imgUrlList.add("http://image.daydayrise.net/360@2x.png");
            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL,imgUrlList);// 图片地址
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CustomApplication.mTencent.shareToQzone(AppQRCodeActivity.this, params, mIUiListener);
                }
            });
        }

    }

}
